#include "packet.h"
#include "netcom.h"
#include "pmb5010.h"
#include "pms5005.h"
#include <stdio.h>

int main(int argc, char *argv[])
{
	packet_t *packet = NULL;
	uint8_t stream[MAX_PACKET_LEN];
	uint8_t jstream[MAX_PACKET_LEN];
	uint8_t ackstream[MAX_PACKET_LEN];
	conn_t *conn = NULL;
	uint8_t start = 1;
	FILE *f = NULL;

	connection_new_robot(&conn, "192.168.0.202", 10001);

	packet = ping_pms5005();
	packet_serialize(packet, stream);

	connection_send_stream(conn, stream, packet_stream_length(stream));

	packet = get_picture();
	packet_serialize(packet, jstream);
	connection_send_stream(conn, jstream, 
				packet_stream_length(jstream));

	while (1) {
		uint16_t len = 0;

	//	while ( stream[INDEX_DID] != JPEG_PACKET && start) {
			FILE *g;

			g = fopen("/tmp/preheader.dat", "a");
//			connection_send_stream(conn, jstream, 
//						packet_stream_length(jstream));

			connection_recv_stream(conn, stream, &len);
			fprintf(stderr, "DID: %d; size :%d\n", 
						stream[INDEX_DID],
						len);
			fwrite(stream, 1, len,  g);
			fputs("xxxx", g);
			fclose(g);
	//	}
		start = 0;

		f = fopen("/tmp/abc.dat", "a");
		fwrite(stream, 1, len, f);
		fputs("0123456789",f);
		puts("____________________________");
//		print_packet_stream(stderr, stream);
//		sleep(1);

//		connection_recv_stream(conn, stream, &len);
		fwrite(stream, 1, len, f);
		fclose(f);
		
		fprintf(stderr, "DID=%x:LEN=%x:DATA=%x", stream[4],
						stream[5],
						stream[6]);

		switch ( stream[INDEX_DID] ) {
			case JPEG_PACKET:
				fprintf(stderr, " < ----- JPG packet!\n");
				print_packet_stream(stderr, stream);
				break;
			case SYSTEM_COM:
				fprintf(stderr, " PING/ACK\n");
			default:
				fprintf(stderr, "\n");

		}

		if ( 0 == len ) {
			break;
		}
	}

	packet_delete(packet);

	return 0;
}
